//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using CommunityServer.Controls;

namespace CommunityServer.Galleries.Controls
{
	/// <summary>
	/// Extends the pager control to be able to page by PostID's when using a pagesize of 1
	/// </summary>
	public class PostPager : Pager
	{
		public virtual SortedList PostIndex 
		{
			get 
			{
				Object state = ViewState["PostIndex"];
				if ( state != null ) 
				{
					return (SortedList)state;
				}
				return new SortedList() ;
			}
			set 
			{
				ViewState["PostIndex"] = value;
			}
		}

		/// <summary>
		/// Determine the page that this post would be on
		/// </summary>
		/// <param name="PostID"></param>
		/// <returns></returns>
		public int GetPage(int PostID)
		{
			return this.PostIndex.IndexOfValue(PostID) / this.PageSize;
		}

		/// <summary>
		/// Determine the postID from the page index
		/// </summary>
		/// <param name="pageIndex">must be an integer</param>
		/// <returns></returns>
		private string GetPostID(string pageIndex)
		{
			int i = int.Parse(pageIndex) -1;
			if(i >= PostIndex.Count)
				return "";

			return this.PostIndex.GetByIndex(i).ToString(); 
		}

		/// <summary>
		/// Merge the PostID into the URL for the pager link
		/// </summary>
		/// <param name="PostID"></param>
		/// <returns></returns>
		public virtual string GetURL(int PostID)
		{
			//determine if we should page by pages or by postID
			//by default this function uses PostID's if the page size is set to 1
			if(this.PageSize == 1)
				return string.Format(this.UrlPattern , PostID);
			else
				return string.Format(this.UrlPattern , GetPage(PostID)); 
		}

		/// <summary>
		/// Overload the original funciton and convert pages into postIDs for URL formatting
		/// </summary>
		/// <param name="pageIndex"></param>
		/// <returns></returns>
		protected override string CreatePagerURL(string pageIndex)
		{
			return base.CreatePagerURL (GetPostID(pageIndex));
		}

	}
}
